<?php


namespace App\Services\Pm;

use App\Common\Api\SystemCode;
use App\Common\Api\SystemMessage;
use App\Services\BaseServices;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Exception;

class UserServices extends BaseServices
{
    const LOGIN_TYPE = 1;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param $params
     */
    public function login($params)
    {
        try {
            if (self::LOGIN_TYPE) {
                /**
                 * 如果是账号密码登录，创建用户时，密码需要Hash处理
                 *  $pass = Hash::make('123456');
                 */
                $token =  JWTAuth::attempt($params);
            } else {
                //手机短信短信,小程序，第三方登录
                $userData = User::query()->where(['id'=>163])->first();
                $token = JWTAuth::fromUser($userData);
            }
            if (!$token) {
                return response()->json([
                    'code'=>SystemCode::SYSTEM_ERROR_USER_OR_PASS,
                    'message'=>SystemMessage::SYSTEM_ERROR_USER_OR_PASS,
                    'data'=>[]
                ])->setStatusCode(Response::HTTP_OK);
            }

            //用户信息;
            $user = JWTAuth::setToken($token)->authenticate();
            $userInfo = $user->toArray();
            $userInfo['token'] = $token;
            return response()->json([
                'code' => SystemCode::SYSTEM_LOGIN_SUCCESS,
                'message'=> SystemMessage::SYSTEM_LOGIN_SUCCESS,
                'data'=>$userInfo
            ])->setStatusCode(Response::HTTP_OK);
        } catch (JWTException $e) {
            return response()->json([
                'code' => SystemCode::SYSTEM_LOGIN_FAIL,
                'message'=>SystemMessage::SYSTEM_LOGIN_FAIL,
                'data'=>[]
            ])->setStatusCode(Response::HTTP_OK);
        }
    }

    /**
     * 刷新Token
     */
    public function refresh()
    {
        try {
            $oldToken = JWTAuth::getToken();
            $token = JWTAuth::refresh($oldToken);
            JWTAuth::invalidate($oldToken);
            return response()->json([
                'code' => SystemCode::SYSTEM_SUCCESS,
                'message'=>SystemMessage::SYSTEM_SUCCESS,
                'data'=>[
                    'token'=>$token,
                    'type'=>'Bearer',
                    'expires'=>JWTAuth::factory()->getTTL() * 60,
                ]
            ])->setStatusCode(Response::HTTP_OK);
        } catch (Exception $e) {
            if ($e instanceof TokenExpiredException) {
                return response()->json([
                    'code' => SystemCode::SYSTEM_TOKEN_EXPIRED,
                    'message' => SystemMessage::SYSTEM_TOKEN_EXPIRED,
                    'data' => []
                ])->setStatusCode(Response::HTTP_OK);
            } else if ($e instanceof TokenInvalidException) {
                return response()->json([
                    'code' => SystemCode::SYSTEM_TOKEN_INVALID,
                    'message' => SystemMessage::SYSTEM_TOKEN_INVALID,
                    'data' => []
                ])->setStatusCode(Response::HTTP_OK);
            } else if ($e instanceof JWTException) {
                return response()->json([
                    'code' => SystemCode::SYSTEM_TOKEN_NOT_EMPTY,
                    'message' => SystemMessage::SYSTEM_TOKEN_NOT_EMPTY,
                    'data' => []
                ])->setStatusCode(Response::HTTP_OK);
            } else if ($e instanceof TokenBlacklistedException) {
                //token列入黑单
                return response()->json([
                    'code' => SystemCode::SYSTEM_TOKEN_LOGOFF,
                    'message' => SystemMessage::SYSTEM_TOKEN_LOGOFF,
                    'data' => []
                ])->setStatusCode(Response::HTTP_OK);
            }
        }
    }

    /**
     * 获取用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfo()
    {
        $userInfo = JWTAuth::parseToken()->authenticate();
        return response()->json([
            'code' => SystemCode::SYSTEM_SUCCESS,
            'msg' => SystemMessage::SYSTEM_SUCCESS,
            'data' => $userInfo,
         ])->setStatusCode(Response::HTTP_OK);
    }

    /**
     * 退出
     */
    public function logout()
    {
        try {
            JWTAuth::parseToken()->invalidate();
            return response()->json([
                'code' =>SystemCode::SYSTEM_LOGOUT_SUCCESS,
                'message'=>SystemMessage::SYSTEM_LOGOUT_SUCCESS,
                'data'=>[]
            ])->setStatusCode(Response::HTTP_OK);
        } catch (JWTException $exception) {
            return response()->json([
                'code' =>SystemCode::SYSTEM_LOGOUT_FAIL,
                'message'=>SystemMessage::SYSTEM_LOGOUT_FAIL,
                'data'=>[]
            ])->setStatusCode(Response::HTTP_OK);
        }
    }
}